package com.jcfk.system.service;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.jcfk.common.web.domain.LoginInfo;
import com.jcfk.system.api.utils.LoginUserInfoUtils;
import com.jcfk.system.domain.dto.*;
import com.jcfk.system.domain.po.*;
import com.jcfk.system.domain.query.OaKeyworkDailyQuery;
import com.jcfk.system.dao.OaKeyworkDailyDao;
import com.jcfk.system.dao.OaKeyworkDailyDao;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

import java.util.ArrayList;
import java.util.List;

import java.util.Date;
import java.util.stream.Collectors;

/**
 * 日报计划事项
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-04-01
 */
@Service
public class OaKeyworkDailyService extends BaseService<OaKeyworkDailyDao, OaKeyworkDaily> {


    @Autowired
    private OaKeyworkDailyDetailService oaKeyworkDailyDetailService;

    @Autowired
    private SysAnnexesFileService sysAnnexesFileService;

    @Autowired
    private SysOrganizationService sysOrganizationService;

    @Autowired
    private RefUserOrganizationMappingService refUserOrganizationMappingService;

    /**
     * OaKeyworkDaily分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<OaKeyworkDailyDTO> queryByPage(DataPage<OaKeyworkDailyDTO> page, OaKeyworkDailyQuery query) {
        OrderItem orderItem = new OrderItem();
        List<OrderItem> orders = new ArrayList<>();
        orderItem.setAsc(false);
        orderItem.setColumn("create_time");
        orders.add(orderItem);
        page.setOrders(orders);

        // 分页查询
        query.setDailyDetail(StringUtils.isEmpty(query.getDailyDetail()) ? query.getDailyDetail() : query.getDailyDetail() + "%");
        query.setCreatedUserName(StringUtils.isEmpty(query.getCreatedUserName()) ? query.getCreatedUserName() : "%" + query.getCreatedUserName() + "%");


        LoginInfo loginInfo = LoginUserInfoUtils.getUserInfo();

        if (query.getCreatedUserId() == null) {
            // 超级管理员
            if (!"superadmin".equals(loginInfo.getUserType())) {
                List<String> userids = getuserIds();
                query.setUserIds(userids);
                if (userids.size() == 0) {
                    return page;
                }
            }

        }
        page = this.baseMapper.queryByPage(page, query);

        return page;
    }

    public List<String> getuserIds() {
        List<String> userids = new ArrayList<>();
        List<SysOrganizationDTO> sysOrganizationDTOS = LoginUserInfoUtils.getUserOrgans();
        List<String> allids = sysOrganizationDTOS.stream().map(SysOrganizationDTO::getAllId).collect(Collectors.toList());
        if (allids.size() == 0)
            return userids;

        QueryWrapper<SysOrganization> sysOrganizationQueryWrapper = new QueryWrapper<>();
        sysOrganizationQueryWrapper.lambda().eq(SysOrganization::getDeleted, 0);
        if (allids.size() > 0) {
            sysOrganizationQueryWrapper.lambda().and(wapper -> {
                for (String id : allids) {
                    wapper.or().likeRight(SysOrganization::getAllId, id);
                }
            });
        }
        List<SysOrganization> list = sysOrganizationService.list(sysOrganizationQueryWrapper);
        if (list.size() == 0) return userids;

        List<String> orgids = list.stream().map(SysOrganization::getId).collect(Collectors.toList());

        QueryWrapper<RefUserOrganizationMapping> refUserOrganizationMappingQueryWrapper = new QueryWrapper<>();
        refUserOrganizationMappingQueryWrapper.lambda().in(RefUserOrganizationMapping::getOrganizationId, orgids);
        List<RefUserOrganizationMapping> users = refUserOrganizationMappingService.list(refUserOrganizationMappingQueryWrapper);
        userids = users.stream().map(RefUserOrganizationMapping::getUserId).collect(Collectors.toList());
        return userids;

    }


    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<OaKeyworkDailyDTO>
     */
    public List<OaKeyworkDailyDTO> getList(OaKeyworkDailyQuery query) {
        // 查询条件
        QueryWrapper<OaKeyworkDaily> qw = new QueryWrapper<>();
        qw.lambda().ge(!StrUtil.isEmpty(query.getWorkDayStart()), OaKeyworkDaily::getWorkDay, query.getWorkDayStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getWorkDayEnd()), OaKeyworkDaily::getWorkDay, query.getWorkDayEnd());
        qw.lambda().like(!StrUtil.isEmpty(query.getDailyDetail()), OaKeyworkDaily::getDailyDetail, query.getDailyDetail());
        // 查询数据
        List<OaKeyworkDaily> list = super.list(qw);

        return convertList(list, OaKeyworkDailyDTO.class);
    }

    /**
     * 获取根据关联id详情表列表
     *
     * @param query 查询条件
     * @return List<OaKeyworkDailyDTO>
     */
    public List<OaKeyworkDailyDetailDTO> getDetails(OaKeyworkDailyQuery query) {
        // 查询条件
        QueryWrapper<OaKeyworkDailyDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getId()), OaKeyworkDailyDetail::getDailyId, query.getId());

        // 查询数据
        List<OaKeyworkDailyDetail> list = oaKeyworkDailyDetailService.list(qw);

        return convertList(list, OaKeyworkDailyDetailDTO.class);
    }


    /**
     * 判断OaKeyworkDaily是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(OaKeyworkDailyDTO dto) {
        QueryWrapper<OaKeyworkDaily> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        return RetResult.ok();
    }

    /**
     * 插入日报计划事项
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(OaKeyworkDailyDTO dto) {

        // 保存
        OaKeyworkDaily item = new OaKeyworkDaily();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);

        // 设置关联主键
        for (OaKeyworkDailyDetailDTO detail : dto.getDetails()) {
            detail.setDailyId(item.getId());
        }

        // 保存明细表
        oaKeyworkDailyDetailService.saveBatch(dto.getDetails(), item.getId());
    }


    /**
     * 更新日报计划事项
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(OaKeyworkDailyDTO dto) {

        // 保存
        OaKeyworkDaily item = new OaKeyworkDaily();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);

        // 设置关联主键
        for (OaKeyworkDailyDetailDTO detail : dto.getDetails()) {
            detail.setDailyId(dto.getId());
        }
        // 保存明细表
        oaKeyworkDailyDetailService.saveBatch(dto.getDetails(), item.getId());
    }


    /**
     * 根据批量主键删除日报计划事项(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(OaKeyworkDailyDTO dto) {

        OaKeyworkDaily item = new OaKeyworkDaily();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<OaKeyworkDaily> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(OaKeyworkDaily item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreatedUserName(SecurityUtils.getUserName());
            item.setCreateTime(new Date());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());
        item.setLastUpdatedUserName(SecurityUtils.getUserName());
        item.setDeleted(0);
    }


    /**
     * 根据主键获取日报计划事项信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public OaKeyworkDailyDTO get(String id) {

        OaKeyworkDaily item = this.baseMapper.selectById(id);
        OaKeyworkDailyDTO dto = new OaKeyworkDailyDTO();

        QueryWrapper<OaKeyworkDailyDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("daily_id", id);
        List<OaKeyworkDailyDetail> list = oaKeyworkDailyDetailService.list(queryWrapper);

        dto.setDetails(convertList(list, OaKeyworkDailyDetailDTO.class));

        for (OaKeyworkDailyDetailDTO detail : dto.getDetails()) {
            SysAnnexesFileDTO sysAnnexesFileDTO = new SysAnnexesFileDTO();

            QueryWrapper<SysAnnexesFile> query = new QueryWrapper<>();
            query.eq("owner_id", detail.getId());
            query.eq("owner_type", "daily_detail_file");

            SysAnnexesFile sysAnnexesFile = sysAnnexesFileService.getOne(query);
            if (sysAnnexesFile != null) {

                BeanUtils.copyProperties(sysAnnexesFile, sysAnnexesFileDTO);

                detail.setFile(sysAnnexesFileDTO);
            }
        }

        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }
        return dto;
    }
}

